package aip.ui.user.srvc;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import aip.core.dao.user.ContactsDao;
import aip.core.model.user.Contacts;
import aip.ui.user.util.ProvinceUtils;
import aip.ui.user.web.spring.ContactsEditForm;
import aip.ui.user.web.spring.ContactsListForm;

import com.googlecode.horncomb.bean.order.DefaultOrder;
import com.googlecode.horncomb.bean.order.DefaultOrderToken;
import com.googlecode.horncomb.bean.order.Order;
import com.googlecode.horncomb.bean.paged.PagedList;
import com.googlecode.horncomb.bean.paged.PagedSetting;

/**
 * Contacts form service
 * <p>
 * 负责人/principal:<br/>
 * 修改记录/revision:<br/>
 * 日期:<br/>
 * 修改人:<br/>
 * 修改说明:<br/>
 * @author
 * @version $Id$
 */
public class ContactsFormService
{
    private ContactsDao contactsDao;

    /**
     * Contacts列表
     * @param form
     *        表单对象
     * @return 列表页面数据
     * @throws Exception
     */
    public Map<String, Object> listReference(ContactsListForm form)
            throws Exception
    {
        Map<String, Object> ref = new HashMap<String, Object>();
        PagedSetting ps = form.getPagedSettingMap().values().iterator().next();
        PagedList<List<? extends Contacts>> result = this.contactsDao.queryAll(
                ps.getOrder(), ps.getPage(), ps.getPageSize());
        ref.put("contactsList", result.getSource()); //$NON-NLS-1$
        ref.put("totalRows", result.getNrOfElements()); //$NON-NLS-1$
        ref.put("provinceMap", ProvinceUtils.provinceMap);
        return ref;
    }

    /**
     * 删除选中的项
     * @param form
     *        表单对象
     * @throws Exception
     */
    public void deleteItems(ContactsListForm form) throws Exception
    {
        if (form.getSelectedIds().size() > 0)
        {
            this.contactsDao.deleteByIds(form.getSelectedIds());
        }
    }

    /**
     * 获得Contacts表单主对象
     * @param form
     *        表单对象
     * @throws Exception
     */
    public void get(ContactsEditForm form) throws Exception
    {
        if (StringUtils.hasText(form.getId()))
        {
            Contacts contacts = this.contactsDao.getById(form.getId());
            BeanUtils.copyProperties(contacts, form);
        }
    }

    /**
     * 显示编辑Contacts界面相关数据
     * @param form
     *        表单对象
     * @return 显示页面数据
     * @throws Exception
     */
    public Map<String, Object> showReference(ContactsEditForm form)
            throws Exception
    {
        // other reference data
        Map<String, Object> ref = new HashMap<String, Object>();
        ref.put("provinceMap", ProvinceUtils.provinceMap);
        return ref;
    }

    /**
     * 前台页面显示相关数据
     * @param form
     *        表单对象
     * @return 显示页面数据
     * @throws Exception
     */
    public Map<String, Object> showInfo(ContactsEditForm form) throws Exception
    {
        // other reference data
        Map<String, Object> ref = new HashMap<String, Object>();
        if (StringUtils.hasText(form.getProvince()))
        {
            List<? extends Contacts> contactsList = this.contactsDao
                    .queryByProvince(form.getProvince());
            ref.put("contactsList", contactsList);
        }
        else
        {
            Order order = new DefaultOrder(new DefaultOrderToken("ORDER_"));
            List<? extends Contacts> contactsList = this.contactsDao
                    .queryAll(order);
            ref.put("contactsList", contactsList);
        }
        ref.put("provinceMap", ProvinceUtils.provinceMap);
        return ref;
    }

    /**
     * 保存Contacts表单
     * @param form
     *        表单对象
     * @throws Exception
     */
    public void save(ContactsEditForm form) throws Exception
    {
        this.contactsDao.save(form);
        this.writeXMl();
    }

    /**
     * 删除单个Contacts
     * @param form
     *        表单对象
     * @throws Exception
     */
    public void deleteItem(ContactsEditForm form) throws Exception
    {
        this.contactsDao.deleteById(form.getId());
    }

    /**
     * 修改XML文件
     * @throws Exception
     */
    @SuppressWarnings("deprecation")
    public void writeXMl() throws Exception
    {
        try
        {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes()).getRequest();
            String fileName = request.getRealPath("user") + "\\d.xml";
            File f = new File(fileName);
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(f);
            doc.normalize();
            NodeList nl = doc.getElementsByTagName("area");
            int nlLength = nl.getLength();
            // 删除已有的内容
            for (int i = 0; i < nlLength; i++)
            {
                doc.getFirstChild().removeChild(
                        doc.getElementsByTagName("area").item(0));
            }
            NodeList nlt = doc.getFirstChild().getChildNodes();
            for (int i = 0; i < nlt.getLength(); i++)
            {
                doc.getFirstChild().removeChild(nlt.item(i));
            }
            // 重写XML
            List<? extends Contacts> contactsList = this.contactsDao
                    .queryAll(null);
            // 拼地区人员电话名称
            Map<String, String> provinceMap = new HashMap<String, String>();
            for (Contacts entity : contactsList)
            {
                String province = entity.getProvince();
                String telName = entity.getTitle().concat("<br>")
                        .concat(entity.getContactPerson()).concat(":")
                        .concat(entity.getTelephone());
                if (provinceMap.get(province) != null)
                {
                    telName = entity.getTitle().concat("<br>")
                            .concat(entity.getContactPerson())
                            .concat(entity.getTelephone()).concat("<br>")
                            .concat(telName);
                }
                provinceMap.put(province, telName);
            }

            for (String province : provinceMap.keySet())
            {
                Element el = doc.createElement("area");
                el.setAttribute("id", province);
                el.setAttribute("title",
                        ProvinceUtils.provinceMap.get(province));
                el.setAttribute("value", provinceMap.get(province));
                el.setAttribute("url",
                        "contacts.shtml?province=".concat(province));
                //el.setAttribute("target", "_blank");
                doc.getFirstChild().appendChild(el);
            }
            this.xml2File(doc, fileName);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    /**
     * 将xml文件保存成文件
     */
    public void xml2File(Document document, String filename)
    {
        try
        {
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            DOMSource source = new DOMSource();
            source.setNode(document);
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            StreamResult result = new StreamResult(new File(filename));
            transformer.transform(source, result);
        }
        catch (TransformerException mye)
        {
            mye.printStackTrace();
        }
    }

    /**
     * @param contactsDao
     *        the contactsDao to set
     */
    public void setContactsDao(ContactsDao contactsDao)
    {
        this.contactsDao = contactsDao;
    }
}
